import deepMerge from "@/uview-ui/libs/function/deepMerge.js";
class Request {
	constructor(arg) {
		this.config = {
			baseUrl: "",
			header: {

			},
			method: "POST",
			timeout: 8000,
			hasToken: true,
			showLoading: true,
			loadingText: "",
			loadingMask: true,
			originalData: true,
			loadingTime: 0,
			timer: null,
			requestBody: {
				data: null,
				timestamp: null
			},
			appInfo: {}
		};

		//拦截器
		this.interceptor = {
			//请求拦截
			request: null,
			//响应拦截
			response: null,
		};

		this.get = (url, data = {}, header = {}) => {
			return this.request({
				method: "get",
				url,
				header,
				data,
			});
		};

		this.post = (url, data = {}, header = {}) => {
			return this.request({
				url,
				method: "post",
				header,
				data,
			});
		};
	}

	setConfig(customConfig) {
		this.config = deepMerge(this.config, customConfig);
	}

	request(options = {}) {
		//检查请求拦截器
		if (
			this.interceptor.request &&
			typeof this.interceptor.request === "function"
		) {
			let interceptorRequest = this.interceptor.request(options);
			if (interceptorRequest === false) {
				// 返回一个处于pending状态中的Promise，来取消原promise，避免进入then()回调
				return new Promise(() => {});
			}
			this.options = interceptorRequest;
		}
		options.url = this.config.baseUrl + options.url;


		options.params = options.params || {};
		options.header = Object.assign({}, this.config.header, options.header);
		options.method = options.method || this.config.method;
		options.timeout = this.config.timeout;
		options.timestamp = new Date().getTime();

		Object.assign(this.config.requestBody, {
			data: JSON.stringify(options.data),
			timestamp: options.timestamp
		});


		options.sign = JSON.stringify(options.data) + options.timestamp;
		for (let i = 0; i < 25; i++) {
			options.sign = uni.$zx.md5Str(options.sign);
		}

		options.data = Object.assign(this.config.requestBody);
		options.token = uni.getStorageSync('token');
		console.log("token=" + options.token)
		Object.assign(this.config.appInfo, {
			"sign": options.sign,
			"appName": "银迅伙伴代理端",
			"name": "yxhb",
			"platform": "H5",
			"jPushDeviceId": "160a3797c90a8f90e4d",
			"loginToken": options.token,
			"appNo": "1000",
			"appVersion": "1.0",
			"systemVersion": "1.0"
		});
		Object.assign(options.header, {
			"app-info": encodeURI(JSON.stringify(this.config.appInfo), "UTF-8")
		});
		console.log(
			"request :>> " +
			"[ " +
			options.method +
			" ] " +
			options.url +
			JSON.stringify(options.data)
		);
		return new Promise((resolve, reject) => {
			options.complete = (response) => {
				// 停止下拉刷新
				uni.stopPullDownRefresh();
				// console.log("code=" + response.data.code)

				if (!response.data.code) {
					uni.$zx.msg(response.data.message, {
						duration: 4000,
					});
				}

				if (response.data.code === 404) {
					uni.$zx.msg("Error: 404", {
						duration: 4000,
					});
				}
				if (response.data.code === 401 || response.data.code === 402) {
					//token失效
					uni.$zx.msg("token失效，请重新登录", {
						duration: 4000,
					});
					uni.reLaunch({
						url: "/pages/main/login/login",
					});
				}
				if (response.data.code !== 200) {
					uni.$zx.msg(response.data.message, {
						duration: 2000,
					});
				}
				//请求完成,隐藏加载
				uni.hideLoading();
				// 清除定时器
				clearTimeout(this.config.timer);
				this.config.timer = null;
				//是否需要返回原始数据


				if (this.config.originalData) {
					// 判断是否存在拦截器

					if (
						this.interceptor.response &&
						typeof this.interceptor.response === "function"
					) {
						let resInterceptors = this.interceptor.response(response);

						if (resInterceptors !== false) {
							resolve(resInterceptors);
						} else {
							reject(response);
						}
					} else {
						// 没有拦截器 返回原始数据
						resolve(response);
					}
				} else {
					// 不返回原始数据
					if (response.data.code == 200) {

						if (
							this.interceptor.response &&
							typeof this.interceptor.response === "function"
						) {
							let resInterceptors = this.interceptor.response(response);
							if (resInterceptors !== false) {
								resolve(resInterceptors);
							} else {
								reject(response.data.data);
							}
						} else {
							resolve(response.data.data);
						}
					} else {
						//不返回原始数据情况下，服务状态非200
						reject(response);
					}
				}
			};

			if (this.config.showLoading && !this.config.timer) {
				this.config.timer = setTimeout(() => {
					uni.showLoading({
						title: this.config.loadingText,
						mark: this.config.loadingMask,
					});
					this.config.timer = null;
				}, this.config.loadingTime);
			}

			uni.request(options);
		});
	}
}

export default new Request();